import {ExceptionFilter,Catch,ArgumentsHost,HttpException,} from '@nestjs/common';
import {Response} from 'express';

@Catch(HttpException) // catch HttpException only
export class HttpExceptionFilter implements ExceptionFilter {
    /**
     * Catch HttpException and return custom error response.
     * Also Catch Pipe Exception and return custom error response.
     */
    catch(exception: HttpException, host: ArgumentsHost) {
        console.log('HttpExceptionFilter 捕获到异常:', exception);
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const req = ctx.getRequest<Request>();
        const status = exception.getStatus();

        // Get Original Exception response data.
        const exceptionResponse = exception.getResponse();

        // Distiguish between custom exception and default exception.
        const errorResponse = {
            status,
            path: req.url,
            // Keep pipe error message.
            message: this.extractExceptionMessage(exceptionResponse),
            // error time
            timestamp: new Date().toISOString(),
        }

        response.status(status).json(errorResponse);
    }

    private extractExceptionMessage(exceptionResponse: any) {
        if(typeof exceptionResponse === 'string') {
            return exceptionResponse;
        }
        if(typeof exceptionResponse === 'object' && 'message' in exceptionResponse) {
            return exceptionResponse.message || exceptionResponse.error;
        }
        return 'Server Internal Error';
    }

}